<template>
  <div class="ai-pre-claim-list">
    <!-- 页面标题 -->
    <el-page-header
        @back="handleBack"
        content="预赔申请列表"
        class="page-header"
    />

    <!-- 查询条件区域 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <!-- 报案号模糊查询 -->
        <el-col :span="6">
          <el-input
              v-model="searchForm.reportId"
              placeholder="请输入报案号"
              clearable
              @keyup.enter="handleSearch"
          />
        </el-col>
        <!-- 审核结果查询 -->
        <el-col :span="6">
          <el-select
              v-model="searchForm.reviewResult"
              placeholder="请选择审核结果"
              clearable
          >
            <el-option label="通过" value="1" />
            <el-option label="部分通过" value="2" />
            <el-option label="驳回" value="3" />
          </el-select>
        </el-col>
        <!-- 预赔状态查询 -->
        <el-col :span="6">
          <el-select
              v-model="searchForm.preClaimStatus"
              placeholder="请选择预赔状态"
              clearable
          >
            <el-option label="查看所有状态" value="" />
            <el-option label="待审核" value="1" />
            <el-option label="审核通过" value="2" />
            <el-option label="部分通过" value="3" />
            <el-option label="已驳回" value="4" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 列表区域 -->
    <el-card class="table-card">
      <el-table
          :data="tableData"
          border
          stripe
          v-loading="loading"
          element-loading-text="加载中..."
          :empty-text="loading ? '加载中...' : '暂无数据'"
      >
        <el-table-column type="index" label="序号" width="80" :index="getSequenceNumber" />
        <el-table-column prop="preClaimId" label="预赔ID" width="100" />
        <el-table-column prop="reportId" label="报案号" width="150" />
        <el-table-column prop="registrationId" label="立案ID" width="150" />
        <el-table-column prop="policyId" label="保单编号" width="150" />
        <el-table-column prop="insuredId" label="投保人ID" width="150" />
        <el-table-column
            prop="farmerApplyTime"
            label="农户申请时间"
            width="200"
            :formatter="formatDateTime"
        />
        <el-table-column
            prop="farmerExpectedAmount"
            label="农户理想赔付金额"
            width="180"
            :formatter="formatMoney"
        />
        <el-table-column
            prop="reviewResult"
            label="审核结果"
            width="120"
            :formatter="formatReviewResult"
        />
        <el-table-column
            prop="approvedAmount"
            label="批准预赔金额"
            width="180"
            :formatter="formatMoney"
        />
        <el-table-column
            prop="preClaimStatus"
            label="预赔状态"
            width="120"
            :formatter="formatPreClaimStatus"
        />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
                type="text"
                @click="handleDetail(scope.row, scope.$index)"
                size="small"
            >
              详情
            </el-button>
            <el-button
                type="primary"
                @click="handleAudit(scope.row, scope.$index)"
                size="small"
                :disabled="scope.row.preClaimStatus !== 1"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.pageNum"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[2, 5, 10, 20]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="预赔申请详情"
        width="70%"
        :close-on-click-modal="false"
    >
      <el-form :model="detailForm" label-width="160px" class="detail-form">
        <el-row :gutter="30">
          <!-- <el-col :span="12">
            <el-form-item label="序号">
              <el-input :value="detailForm.sequenceNumber" disabled />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="关联报案ID">
              <el-input v-model="detailForm.reportId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联立案ID">
              <el-input v-model="detailForm.registrationId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联保单编号">
              <el-input v-model="detailForm.policyId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联投保人ID">
              <el-input v-model="detailForm.insuredId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预赔状态">
              <el-input v-model="detailForm.preClaimStatus" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="农户申请时间">
              <el-input v-model="detailForm.farmerApplyTime" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="农户理想赔付金额">
              <el-input v-model="detailForm.farmerExpectedAmount" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请理由">
              <el-input v-model="detailForm.applyReason" type="textarea" rows="2" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请证明材料">
              <el-input v-model="detailForm.applyEvidence" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核领导ID">
              <el-input v-model="detailForm.reviewerId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核时间">
              <el-input v-model="detailForm.reviewTime" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核结果">
              <el-input v-model="detailForm.reviewResult" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批准预赔金额">
              <el-input v-model="detailForm.approvedAmount" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审核意见">
              <el-input
                  v-model="detailForm.reviewOpinion"
                  type="textarea"
                  rows="3"
                  disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog
        v-model="auditDialogVisible"
        title="预赔申请审核"
        width="70%"
        :close-on-click-modal="false"
    >
      <el-form
          :model="auditForm"
          label-width="160px"
          :rules="auditRules"
          ref="auditFormRef"
          class="audit-form"
      >
        <el-row :gutter="30">
          <!-- 只读基础信息 -->
          <!-- <el-col :span="12">
            <el-form-item label="序号">
              <el-input :value="auditForm.sequenceNumber" disabled />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="报案号">
              <el-input v-model="auditForm.reportId" disabled />
            </el-form-item>
          </el-col>
          <!-- 审核必填项 -->
          <el-col :span="12">
            <el-form-item label="审核员" prop="reviewerId">
              <el-select
                  v-model="auditForm.reviewerId"
                  placeholder="请选择审核领导"
                  :loading="staffLoading"
                  filterable
                  clearable
                  style="width: 100%"
              >
                <el-option v-for="staff in staffList" :key="staff.workNo"
                :label="`${staff.realName} (${staff.workNo})`" :value="staff.workNo">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核结果" prop="reviewResult">
              <el-select v-model="auditForm.reviewResult" placeholder="请选择审核结果">
                <el-option label="通过" value="1" />
                <el-option label="部分通过" value="2" />
                <el-option label="驳回" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
                label="批准预赔金额"
                prop="approvedAmount"
            >
              <el-input
                  v-model="auditForm.approvedAmount"
                  type="number"
                  step="0.01"
                  placeholder="驳回无需填写"
                  :disabled="auditForm.reviewResult === '3'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预赔状态" prop="preClaimStatus">
              <el-select v-model="auditForm.preClaimStatus" placeholder="请选择预赔状态">
                <!-- <el-option label="待审核" value="1" /> -->
                <el-option label="审核通过" value="2" />
                <el-option label="部分通过" value="3" />
                <el-option label="已驳回" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审核意见" prop="reviewOpinion">
              <el-input
                  v-model="auditForm.reviewOpinion"
                  type="textarea"
                  rows="3"
                  placeholder="请填写审核意见（如：同意按申请金额预赔）"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="审核依据" prop="reviewBasis">
              <el-input
                  v-model="auditForm.reviewBasis"
                  type="textarea"
                  rows="3"
                  placeholder="请填写审核依据（如：农户实际损失情况、公司预赔管理办法）"
              />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveAudit">保存审核</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, unref } from 'vue';
import { ElMessage } from 'element-plus';
import hxxp from '@/utils/hxxp';

// 全局路由对象
const { proxy } = getCurrentInstance();

// 搜索表单
const searchForm = reactive({
  reportId: '',
  reviewResult: '',
  preClaimStatus: '1'
});

// 表格数据与分页
const tableData = ref([]);
const loading = ref(false);
const pagination = reactive({
  pageNum: 1,
  pageSize: 2,
  total: 0
});

// 员工数据
const staffList = ref([]);
const staffLoading = ref(false);

// 详情弹窗相关
const detailDialogVisible = ref(false);
const detailForm = reactive({
  sequenceNumber: '',
  preClaimId: '',
  reportId: '',
  registrationId: '',
  policyId: '',
  insuredId: '',
  preClaimStatus: '',
  farmerApplyTime: '',
  farmerExpectedAmount: '',
  applyReason: '',
  applyEvidence: '',
  reviewerId: '',
  reviewTime: '',
  reviewResult: '',
  approvedAmount: '',
  reviewOpinion: ''
});

// 审核弹窗相关
const auditDialogVisible = ref(false);
const auditFormRef = ref(null);
const auditForm = reactive({
  sequenceNumber: '',
  preClaimId: '',
  reportId: '',
  reviewerId: '',
  reviewResult: '',
  approvedAmount: null,
  reviewOpinion: '',
  reviewBasis: '',
  preClaimStatus: ''
});
const auditRules = reactive({
  reviewerId: [
    { required: true, message: '请选择审核领导', trigger: 'change' }
  ],
  reviewResult: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ],
  preClaimStatus: [
    { required: true, message: '请选择预赔状态', trigger: 'change' }
  ],
  reviewOpinion: [
    { required: true, message: '请填写审核意见', trigger: 'blur' }
  ],
  reviewBasis: [
    { required: true, message: '请填写审核依据', trigger: 'blur' }
  ]
});

// 页面加载时查询数据
onMounted(() => {
  fetchPreClaimList();
  fetchStaffList();
});

/**
 * 查询预赔列表
 */
const fetchPreClaimList = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      reviewResult: searchForm.reviewResult ? Number(searchForm.reviewResult) : undefined,
      preClaimStatus: searchForm.preClaimStatus ? Number(searchForm.preClaimStatus) : undefined,
      reportId: searchForm.reportId || undefined
    };

    const response = await hxxp.get('/aiPreClaim/list', { params });
    console.log(response);
    

    if (response.code === 100200) {
      // 处理数据，确保状态值为数字类型
      const processedData = (response.data.list || []).map(item => ({
        ...item,
        farmerExpectedAmount: normalizeNumber(item.farmerExpectedAmount),
        approvedAmount: normalizeNumber(item.approvedAmount),
        // 强制转换状态值为数字，解决显示异常
        reviewResult: convertToNumber(item.reviewResult),
        preClaimStatus: convertToNumber(item.preClaimStatus)
      }));

      tableData.value = processedData;
      pagination.total = response.data.total || 0;
    } else {
      ElMessage.error(`查询失败：${response.data.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('预赔列表查询异常：', error);
    ElMessage.error('网络异常，查询失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

/**
 * 获取员工列表数据
 */
const fetchStaffList = async () => {
  staffLoading.value = true;
  try {
    const response = await hxxp.get('/aiStaffUser/worker',{
      params: {
        positionCode: 'PTN008'
      }
    });
    
    if (response.code === 100200) {
      staffList.value = response.data || [];
      console.log('员工列表数据:', staffList.value);
    } else {
      ElMessage.error(`获取员工列表失败：${response.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('获取员工列表异常：', error);
    ElMessage.error('网络异常，获取员工列表失败，请稍后重试');
  } finally {
    staffLoading.value = false;
  }
};

// 查询/重置/分页方法
const handleSearch = () => {
  pagination.pageNum = 1;
  fetchPreClaimList();
};

const resetForm = () => {
  searchForm.reportId = '';
  searchForm.reviewResult = '';
  searchForm.preClaimStatus = '1';
  pagination.pageNum = 1;
  fetchPreClaimList();
};

const handleSizeChange = (pageSize) => {
  pagination.pageSize = pageSize;
  fetchPreClaimList();
};

const handleCurrentChange = (pageNum) => {
  pagination.pageNum = pageNum;
  fetchPreClaimList();
};

/**
 * 处理详情弹窗显示 - 核心修复
 */
const handleDetail = (row, index) => {
  // 深拷贝数据，避免引用问题
  const rowData = JSON.parse(JSON.stringify(row));

  // 计算序号
  const sequenceNumber = getSequenceNumber(index);

  // 为每个字段设置默认值，确保不会显示空白
  detailForm.sequenceNumber = sequenceNumber;
  detailForm.preClaimId = rowData.preClaimId || 'N/A';
  detailForm.reportId = rowData.reportId || 'N/A';
  detailForm.registrationId = rowData.registrationId || '无关联立案';
  detailForm.policyId = rowData.policyId || 'N/A';
  detailForm.insuredId = rowData.insuredId || 'N/A';
  // 新增预赔状态显示
  detailForm.preClaimStatus = formatPreClaimStatus(null, null, rowData.preClaimStatus) || '未知';
  detailForm.farmerApplyTime = rowData.farmerApplyTime ? formatDateTime(null, null, rowData.farmerApplyTime) : '未记录';
  detailForm.farmerExpectedAmount = rowData.farmerExpectedAmount ? formatMoney(rowData.farmerExpectedAmount) : '0.00 元';
  detailForm.applyReason = rowData.applyReason || '无申请理由';
  detailForm.applyEvidence = rowData.applyEvidence || '无证明材料';
  detailForm.reviewerId = rowData.reviewerId || '未指定审核人';
  detailForm.reviewTime = rowData.reviewTime ? formatDateTime(null, null, rowData.reviewTime) : '未审核';
  detailForm.reviewResult = formatReviewResult(null, null, rowData.reviewResult) || '未审核';
  detailForm.approvedAmount = rowData.approvedAmount ? formatMoney(rowData.approvedAmount) : '未批准';
  detailForm.reviewOpinion = rowData.reviewOpinion || '无审核意见';

  detailDialogVisible.value = true;
};

// 审核弹窗方法
const handleAudit = (row, index) => {
  // 计算序号
  const sequenceNumber = getSequenceNumber(index);
  
  auditForm.sequenceNumber = sequenceNumber;
  auditForm.preClaimId = row.preClaimId || '';
  auditForm.reportId = row.reportId || '';
  auditForm.reviewerId = row.reviewerId || '';
  auditForm.reviewResult = row.reviewResult ? String(row.reviewResult) : '';
  auditForm.approvedAmount = row.approvedAmount || null;
  auditForm.reviewOpinion = row.reviewOpinion || '';
  auditForm.reviewBasis = row.reviewBasis || '';
  // auditForm.preClaimStatus = row.preClaimStatus ? String(row.preClaimStatus) : '';

  auditDialogVisible.value = true;
};

/**
 * 保存审核结果
 */
const handleSaveAudit = async () => {
  const formRef = unref(auditFormRef);
  if (!formRef) return;

  try {
    await formRef.validate();

    const submitData = {
      ...auditForm,
      reviewResult: Number(auditForm.reviewResult),
      preClaimStatus: Number(auditForm.preClaimStatus),
      approvedAmount: auditForm.approvedAmount ? Number(auditForm.approvedAmount) : null,
      reviewTime: new Date().toISOString().replace('T', ' ').slice(0, 19)
    };

    const response = await hxxp.put('/aiPreClaim/update', submitData);

    if (response.code === 100200) {
      ElMessage.success('审核保存成功！');
      auditDialogVisible.value = false;
      fetchPreClaimList();
    } else {
      ElMessage.error(`保存失败：${response.msg || '未知错误'}`);
    }
  } catch (error) {
    if (error.name === 'Error') {
      console.error('审核保存异常：', error);
      ElMessage.error('网络异常，保存失败，请稍后重试');
    }
    return;
  }
};

/**
 * 日期时间格式化函数
 */
const formatDateTime = (row, column, dateStr) => {
  if (!dateStr) return '-';
  const normalizedDateStr = String(dateStr).replace('T', ' ').split('.')[0];
  const date = new Date(normalizedDateStr);
  if (isNaN(date.getTime())) return '日期无效';

  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(',', '');
};

/**
 * 安全转换为数字
 */
const convertToNumber = (value) => {
  if (value === null || value === undefined) return null;
  if (typeof value === 'number') return value;
  if (typeof value === 'string') {
    const num = Number(value);
    return isNaN(num) ? null : num;
  }
  // 如果是对象类型，尝试获取其数值表示
  if (typeof value === 'object') {
    console.warn('发现异常状态值（对象类型）:', value);
    return null;
  }
  return null;
};

/**
 * 标准化数字（解决NaN问题）
 */
const normalizeNumber = (value) => {
  if (value === null || value === undefined) return null;

  const num = Number(value);
  return isNaN(num) ? null : num;
};

/**
 * 格式化金额显示
 */
const formatMoney = (row, column, cellValue) => {
  // 处理表格formatter调用（三个参数）和直接调用（一个参数）的情况
  const amount = cellValue !== undefined ? cellValue : row;
  
  if (amount === null || amount === undefined || isNaN(amount)) {
    return '0.00 元';
  }

  return Number(amount).toFixed(2) + ' 元';
};

/**
 * 格式化审核结果 - 修复显示异常
 */
const formatReviewResult = (row, column, cellValue) => {
  // 确保输入是有效的数字
  const status = convertToNumber(cellValue);

  if (status === null) return '未知';

  const map = {
    1: '通过',
    2: '部分通过',
    3: '驳回'
  };

  return map[status] || `未知(${status})`;
};

/**
 * 格式化预赔状态 - 修复显示异常
 */
const formatPreClaimStatus = (row, column, cellValue) => {
  // 确保输入是有效的数字
  const status = convertToNumber(cellValue);

  if (status === null) return '未知';

  const map = {
    1: '待审核',
    2: '审核通过',
    3: '部分通过',
    4: '已驳回'
  };

  return map[status] || `未知(${status})`;
};

/**
 * 生成序号
 */
const getSequenceNumber = (index) => {
  return (pagination.pageNum - 1) * pagination.pageSize + index + 1;
};

/**
 * 返回上一页
 */
const handleBack = () => {
  if (proxy?.$router) {
    proxy.$router.back();
  } else {
    window.history.back();
  }
};
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 24px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.table-card {
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.pagination {
  margin-top: 16px;
  text-align: right;
}

.detail-form, .audit-form {
  margin-top: 8px;
}

.el-textarea {
  width: 100%;
}
</style>
